package me.leon.ade

import android.content.ComponentName
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import io.reactivex.Flowable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.net.URL
import java.util.concurrent.TimeUnit
import me.leon.ade.databinding.ActivityMainBinding
import me.leon.ext.android.IntentUtils
import me.leon.ext.android.PermissionUtils
import me.leon.ext.android.SpanUtils
import me.leon.ext.constant.PermissionConstants
import me.leon.keeplive.ExactWorkService
import me.leon.keeplive.OSHelper

class MainActivity : AbsBindingActivity<ActivityMainBinding>() {

    private var disposable: Disposable? = null
    override fun ActivityMainBinding.init() {

        Log.w("Leon666", "MainActivity")
        et.setOnFocusChangeListener { _, hasFocus ->
            et.textAlignment =
                View.TEXT_ALIGNMENT_TEXT_START.takeIf { hasFocus } ?: View.TEXT_ALIGNMENT_CENTER
        }
        et.addTextChangedListener(
            object : TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                    //nop
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                    et.textAlignment =
                        View.TEXT_ALIGNMENT_TEXT_START.takeIf { it.toString().trim().isNotEmpty() }
                            ?: View.TEXT_ALIGNMENT_CENTER
                }

                override fun afterTextChanged(p0: Editable?) {}
            }
        )

        btnWeb.setOnClickListener { WebViewActivity.start(this@MainActivity) }
        btnExtra.setOnClickListener { ToExtraActivity.start(this@MainActivity) }
        //        btnExtra.performClick()

        DialogActivity.start(this@MainActivity)

        PermissionUtils.permission(PermissionConstants.STORAGE, PermissionConstants.CAMERA)
            .callback(
                object : PermissionUtils.SimpleCallback {
                    override fun onGranted() {
                        Log.d("PermissionUtils", "onGranted")
                    }

                    override fun onDenied() {
                        Log.d("PermissionUtils", "onDenied")
                    }
                }
            )
            .request()
        //        Leon.d("app start")
        disposable?.dispose()

        ExactWorkService.addCallback(this@MainActivity) { Log.d("KeepLiveService", "period  ") }

        ExactWorkService.launch(this@MainActivity, 10)

        // 由于系统省电优化的及休眠的影响,执行的时间会有一定的延迟, 若对时间要求较高的建议使用alarm service + receiver
        disposable =
            Flowable.interval(3, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe {
                    if (it % 90 == 0L) {
                        try {
                            Log.d("Flowable", URL("https://www.baidu.com").readText())
                        } catch (e: Exception) {
                            Log.d("Flowable", Log.getStackTraceString(e))
                        }
                    }

                    Leon.d("Flowable", "time tik中文... $it")
                    Leon.v("Flowable", "vv 过滤... $it")
                    runOnUiThread { tvCount.text = "${it * 3L}s" }
                }

        tvShow.text =
            SpanUtils()
                .append("hello")
                .append("RED text")
                .setBold()
                .setForegroundColor(Color.RED)
                .setBold()
                .setFontSize(24, true)
                .append("bold")
                .setBold()
                .append("underline")
                .setUnderline()
                .appendImage(R.drawable.ic_launcher_background, 555)
                .create()

        //            buildSpannedString {
        //                append("hello")
        //                bold {
        //                    color(Color.RED) {
        //                        scale(2f) {
        //
        //                            append("RED text")
        //                        }
        //                    }
        //                    append("bold")
        //                }
        //                underline {
        //                    append("underline")
        //
        //                }
        //
        //            }

        lifecycle.addObserver(StateListener())
        if (!Settings.isLogin) {
            Settings.isLogin = true
        }
        if (!Settings.isShowGuide) {
            Settings.isShowGuide = true
        }
        Log.d("App___2", Settings.isLogin.toString())
        Log.d("App___2", Settings.isShowGuide.toString())

        //        startActivity(Intent(this, ToExtraActivity::class.java).apply {
        //            putExtra("name2", "hell")
        //            putExtra("age", 66)
        //            putExtra("stringArray1", arrayOf("aa", "bb"))
        //            putExtra("stringList", arrayListOf("vv", "dd"))
        //
        //        })

    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onBackPressed() {
        finishAfterTransition()
    }

    fun noBatteryOpt(view: View) {
        OSHelper.goBatteryOptimization()
    }

    fun autoStart(view: View) {
        //        requestAutoStartPermission()
        OSHelper.goAutoStar()
    }

    override fun onResume() {
        super.onResume()

        //        if (!OSHelper.canDrawOverlays()) {
        //            Log.d("FloatWin", "goOveray")
        //            OSHelper.goFloatWindows()
        //            return
        //        }
        //        Log.d("hasBatteryOptimization", "" + OSHelper.hasBatteryOptimization())
        //        if (!Svc.isAccessibilitySettingsOn(this)) {
        //            Log.d("svc", "go settings")
        //            startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
        //        } else {
        //            Log.d("svc", "start svc")
        //            startService(Intent(this, Svc::class.java))
        //        }
    }

    private val cmpList =
        arrayOf(
            "com.coloros.safecenter/.permission.startup.FakeActivity",
            "com.coloros.safecenter/.permission.startupapp.StartupAppListActivity",
            "com.coloros.safecenter/.permission.startupmanager.StartupAppListActivity",
            "com.coloros.safecenter/.permission.startupapp.StartupAppListActivity",
            "com.coloros.safecenter/.startupapp.StartupAppListActivity",
            "com.coloros.safe/.permission.startup.StartupAppListActivity",
            "com.coloros.safe/.permission.startupmanager.StartupAppListActivity",
            "com.coloros.safe/.permission.startupapp.StartupAppListActivity",
            "com.coloros.safecenter/.permission.startupapp.startupmanager",
            "com.coloros.safecenter/.permission.startsettings",
            "com.coloros.safecenter/com.coloros.privacypermissionsentry.PermissionTopActivity",
            "com.coloros.safecenter/com.coloros.privacypermissionsentry.PermissionTopActivity.Startupmanager",
            "com.coloros.safecenter/.FakeActivity",
            "com.coloros.phonemanager/.FakeActivity"
        )

    private fun requestAutoStartPermission() {
        // com.coloros.safecenter.permission.singlepage.PermissionSinglePageActivity
        // listpermissions
        // com.coloros.privacypermissionsentry.PermissionTopActivity
        // privacypermissions
        // getPackageManager().getLaunchIntentForPackage("com.coloros.safecenter");
        if (Build.MANUFACTURER == "OPPO") {

            for (cmp in cmpList) {

                Intent()
                    .apply {
                        component = ComponentName.unflattenFromString(cmp)
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    }
                    .also {
                        //                    if (Build.VERSION.SDK_INT >= 29) {
                        //                        val launchIntentForPackage =
                        //
                        // packageManager.getLaunchIntentForPackage("com.coloros.phonemanager")
                        //                                .also { println(it) }?.run {
                        //                                    if
                        // (packageManager.resolveActivity(this, 0) != null) {
                        //                                        startActivity(this)
                        //                                    }
                        //                                }
                        //
                        //                        return
                        //                    }

                        if (packageManager.resolveActivity(it, 0) != null &&
                                Build.VERSION.SDK_INT < 29
                        ) {
                            println(cmp)
                            startActivity(it)
                            return
                        }
                    }
            }
        }
    }

    fun limitless(view: View) {
        OSHelper.goLimitless()
    }

    override fun onDestroy() {
        super.onDestroy()
        disposable?.dispose()
    }

    fun recentTask(view: View) {
        binding.et.text = null
        binding.et.clearFocus()
        //        OSHelper.goRecent()
    }

    fun notification(view: View) {
        OSHelper.goNotificationSettings(this)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun installPermission(view: View) {

        if (!IntentUtils.hasInstallUnknownPermission()) {
            AlertDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("需要打开安装未知来源应用权限")
                .setPositiveButton(R.string.app_name) { _, _ ->
                    IntentUtils.goUnknownPermissionSettings()
                }
                .setNegativeButton(R.string.app_name) { dialog, _ -> dialog.dismiss() }
                .create()
                .show()
        }
    }
}
